<?php

require_once LIBRARIES_ENTITIES_DATABASE;
require_once LIBRARIES_ENTITIES_CONTACTS;


require_once LIBRARIES_TOOLS_UTILITY;
require_once LIBRARIES_TOOLS_XTEMPLATE;
require_once LIBRARIES_TOOLS_PAGERBACKEND;

class ContactController {

    public function invoke() {

        // function list
        $groupFunctions = $_SESSION['groupFunctions'];

        // directory path
        $dir = dirname(__FILE__);

        $action = '';
        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }



        $task = '';
        if (isset($_GET['task'])) {
            $task = $_GET['task'];
        }

        $view="";
            if(isset($_GET["view"])){
            $view=$_GET["view"];
            }


        switch(trim($view)){

            case "reply":
            include_once($dir . '/views/com_contact.reply.php');
            break;

            }   

            // gửi phản hồi
            if ($action == 'sendmailphanhoi') {
            $mailTo = $_POST['mailTo'];
            $txttieude = $_POST['txttieude'];
            $txtnoidung = $_POST['txtnoidung'];
             
             // Utility::messageBox('Gửi phản hồi thành công');
            function server_parse($socket, $expected_response)
            {
                $server_response = '';
                while (substr($server_response, 3, 1) != ' ')
                {
                    if (!($server_response = fgets($socket, 256)))
                        echo 'Lỗi.', __FILE__, __LINE__;
                }
             
                if (!(substr($server_response, 0, 3) == $expected_response))
                    echo 'Lỗi'.$server_response.'"', __FILE__, __LINE__;
            }
            function smtp_mail($to, $subject, $message, $headers = '')
            {
                $recipients = explode(',', $to);
                $user = 'quantri.bochihuy@gmail.com';
                $pass = 'quantri.bochihuy1';
                $smtp_host = 'ssl://smtp.gmail.com';
                $smtp_port = 465;
         
             
                if (!($socket = fsockopen($smtp_host, $smtp_port, $errno, $errstr, 15)))
                    echo "'Lỗi'$smtp_host' ($errno) ($errstr)", __FILE__, __LINE__;
             
                server_parse($socket, '220');
             
                fwrite($socket, 'EHLO '.$smtp_host."\r\n");
                server_parse($socket, '250');
             
                fwrite($socket, 'AUTH LOGIN'."\r\n");
                server_parse($socket, '334');
             
                fwrite($socket, base64_encode($user)."\r\n");
                server_parse($socket, '334');
             
                fwrite($socket, base64_encode($pass)."\r\n");
                server_parse($socket, '235');
             
             
             
                fwrite($socket, 'MAIL FROM: <example@gmail.com>'."\r\n");
                server_parse($socket, '250');
             
                foreach ($recipients as $email)
                {
                    fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
                    server_parse($socket, '250');
                }
             
                fwrite($socket, 'DATA'."\r\n");
                server_parse($socket, '354');
             
                fwrite($socket, 'Subject: '.$subject."\r\n".'To: <'.implode('>, <', $recipients).'>'."\r\n".$headers."\r\n\r\n".$message."\r\n");
             
                fwrite($socket, '.'."\r\n");
                server_parse($socket, '250');
             
                fwrite($socket, 'QUIT'."\r\n");
                fclose($socket);
             
                return true;
            }
 
     




            // Send the mail
            if(smtp_mail($mailTo,$txttieude,$txtnoidung))
            {
                // echo 'SendMail+#####+OK';
                 Utility::messageBox('Gửi phản hồi thành công');
            }
            else
            {
                // echo 'SendMail+#####+NOOK';
                Utility::messageBox('Gửi phản hồi thất bại');
            }
            

            exit();
    }
     //End gửi phản hồi












        $rowToView = 10;
        if (isset($_POST["limit"])) {
            $rowToView = $_POST["limit"];
        }

        // serID
        $userID = $_SESSION["session"]["sUserID"];


        switch ($action) {
            case 'remove':
                $values = $_POST["cid"];
                $result = $this->deleteContact($values);
                if ($result == OK) {
                    Utility::messageBox('Xóa thành công', './?com=com_contact&task=view');
                }
                break;

             
                case "publish":
                    $values = $_POST["cid"];
                    $result = $this->updateStatus($values, true);
                    break;
                case "unpublish":
                    $values = $_POST["cid"];
                    $result = $this->updateStatus($values, false);
                    break;
            

        }








        if ($task == 'view') {
            // check view permission
            if (Utility::checkPermission('view', $groupFunctions, CONTACT_MANAGEMENT)) {
                $viewFile = $dir . '/views/contact_list.html';
                $xtemplate = new XTemplate($viewFile);

                // CHECK PERMISSION
                // check delete button
                if (Utility::checkPermission('delete', $groupFunctions, CONTACT_MANAGEMENT)) {
                    $xtemplate->parse('main.delete_button');
                }
                 // check enable button
                if (Utility::checkPermission('enable', $groupFunctions, CONTACT_MANAGEMENT)) {
                    $xtemplate->parse('main.enable_button');
                }
                // check disable button
                if (Utility::checkPermission('disable', $groupFunctions, CONTACT_MANAGEMENT)) {
                    $xtemplate->parse('main.disable_button');
                }






                $indexCheckBox = 1;

                $rurrentPage = 1;
                if (isset($_POST["page"])) {
                    $rurrentPage = $_POST["page"];
                }

                // chỉ mục (số thứ tự của bài viết) bài viết
                $index = 1;

                $contacts = $this->getContactList();

                $pager = PagerBackEnd::getPagerData(count($contacts), $rowToView, $rurrentPage);


                if ($contacts != null) {

                    $indexCheckBox = 1;

                    foreach ($contacts as $contact) {

                        if ($index > $pager->offset && $index <= $pager->limit) {

                            $xtemplate->assign('INDEX', $index);
                            $xtemplate->assign('INDEX_CHECKBOX', $indexCheckBox);

                            $xtemplate->assign('ID', $contact->getID());
                            $xtemplate->assign('FULLNAME', $contact->getFullname());
                            $xtemplate->assign('EMAIL', $contact->getEmail());
                            $xtemplate->assign('COMPANY', $contact->getCompany());
                            $xtemplate->assign('FAX', $contact->getFax());
                            $xtemplate->assign('TITLE', $contact->getTitle());
                            $xtemplate->assign('CONTENT', $contact->getContent());
                            $xtemplate->assign('ADDRESS', $contact->getAddress());
                            $xtemplate->assign('PHONE', $contact->getPhone());
                            $xtemplate->assign('CREATED_DATE', Utility::formatDateTimeToView($contact->getCreatedDate()));
                            
                             // status
                                if ($contact->get_status() == 1) {
                                    $xtemplate->assign('STATUS_ACTION', 'unpublish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_g.png');
                                } else {
                                    $xtemplate->assign('STATUS_ACTION', 'publish');
                                    $xtemplate->assign('STATUS_IMAGE', 'publish_r.png');
                                }
                            $xtemplate->parse('main.row');

                            $indexCheckBox++;
                        }
                        $index++;
                    }
                }

                $xtemplate->assign('LIMIT_LIST', Utility::getLimitList($rowToView));
                $xtemplate->assign('ROW_TO_VIEW', $rowToView);
                $xtemplate->assign('CURRENT_PAGE', $rurrentPage);
                $xtemplate->assign('AMOUNT_OF_PAGE', $pager->numPages);
                $xtemplate->assign('PAGING_HTML', $pager->paging);
                $xtemplate->parse('main');
                $xtemplate->out('main');
            } else {
                echo ERROR_PERMISSION;
            }
        }
    }

    private function getContactList() {
        $db = new Database();
        try {
            $contact = new Contacts();
            $result = $contact->getList($db);
            $db->submitChanges();
            return $result;
        } catch (Exception $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }



    // hàm cập nhật trạng thái bài viết
    private function updateStatus($values, $status) {

        try {
            $db = new Database();
            for ($i = 0; $i < count($values); $i++) {
               $contact = new Contacts();
                $contact->setID($values[$i]);
                if ($status == true) {
                    $contact->set_status(1);
                } else {
                    $contact->set_status(0);
                }
                $contact->updateStatus($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            exit();
        }
    }





    private function deleteContact($values) {
        $db = new Database();
        try {
            for ($i = 0; $i < count($values); $i++) {
                $contact = new Contacts();
                $contact->setID($values[$i]);
                $contact->delete($db);
            }
            $db->submitChanges();
            return OK;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}

?>
